package com.yourenbang.lingyun.transaction.web.service.impl.pay;

import com.alibaba.fastjson.JSONObject;
import com.yourenbang.lingyun.constants.BizCodeMessages;
import com.yourenbang.lingyun.constants.Constant;
import com.yourenbang.lingyun.constants.enums.*;
import com.yourenbang.lingyun.constants.enums.mq.MqEnum;
import com.yourenbang.lingyun.constants.enums.table.MerchantEnum;
import com.yourenbang.lingyun.constants.enums.table.PayTransactionEnum;
import com.yourenbang.lingyun.core.config.datasource.DataSources;
import com.yourenbang.lingyun.core.config.datasource.RoutingDataSource;
import com.yourenbang.lingyun.core.message.Result;
import com.yourenbang.lingyun.core.model.vo.PageVO;
import com.yourenbang.lingyun.core.support.PageFrom;
import com.yourenbang.lingyun.core.util.KLog;
import com.yourenbang.lingyun.core.util.NumberUtil;
import com.yourenbang.lingyun.core.util.StringUtils;
import com.yourenbang.lingyun.core.util.date.DateFormat;
import com.yourenbang.lingyun.core.util.date.LocalDateUtils;
import com.yourenbang.lingyun.core.util.http.HttpClientUtil;
import com.yourenbang.lingyun.domain.*;
import com.yourenbang.lingyun.mapper.*;
import com.yourenbang.lingyun.transaction.config.AcmTransactionParams;
import com.yourenbang.lingyun.transaction.mapper.*;
import com.yourenbang.lingyun.transaction.web.domain.dto.BalanceListDTO;
import com.yourenbang.lingyun.transaction.web.domain.dto.KlksBalanceListDTO;
import com.yourenbang.lingyun.transaction.web.domain.dto.KlksBalanceListDetailDTO;
import com.yourenbang.lingyun.transaction.web.domain.dto.TradeListDTO;
import com.yourenbang.lingyun.transaction.web.domain.dto.pay.MqPayTransationDTO;
import com.yourenbang.lingyun.transaction.web.domain.po.FundAccountJournal;
import com.yourenbang.lingyun.transaction.web.domain.po.FundAccountWithdrawPayment;
import com.yourenbang.lingyun.transaction.web.domain.vo.BalanceListVO;
import com.yourenbang.lingyun.transaction.web.domain.vo.TradeDetailVO;
import com.yourenbang.lingyun.transaction.web.domain.vo.TradeListVO;
import com.yourenbang.lingyun.transaction.web.domain.vo.TradeMonthVO;
import com.yourenbang.lingyun.transaction.web.service.CommonService;
import com.yourenbang.lingyun.transaction.web.service.impl.pay.transaction.PayTransactionConfig;
import com.yourenbang.lingyun.transaction.web.service.pay.TradeService;
import com.yourenbang.mcenter.api.model.dto.MqSendMessage;
import com.yourenbang.mcenter.api.service.McenterMqService;
import com.yourenbang.merchant.api.model.dto.GetRealPhoneDTO;
import com.yourenbang.merchant.api.service.yxy.MerchantYxyApiService;
import com.yourenbang.terminal.api.model.dto.RpcYxyTerminalBindDTO;
import com.yourenbang.terminal.api.model.dto.RpcYxyTerminalToBindDTO;
import com.yourenbang.terminal.api.service.RpcYxyTerminalService;
import com.yourenbang.transaction.api.model.dto.fund.QueryMonthAmountDTO;
import com.yourenbang.transaction.api.model.vo.pay.PayTransaction;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <h3>service-transaction</h3>
 * <p></p>
 *
 * @author : jason
 * @date : 2020-08-26 17:21
 **/
@Slf4j
@Service
public class TradeServiceImpl implements TradeService {

    @Autowired
    private TransactionFundBillMapper fundBillMapper;
    @Autowired
    private UserBaseMapper userBaseMapper;
    @Autowired
    private CommonService commonService;
    @Autowired
    private TransactionFundAccountWithdrawPaymentMapper fundAccountWithdrawPaymentMapper;
    @Autowired
    private TransactionUserMapper transactionUserMapper;
    @Autowired
    private TransactionPayTransactionMapper transactionPayTransactionMapper;
    @Autowired
    private AcmTransactionParams acmTransactionParams;
    @Autowired
    private McenterMqService mcenterMqService;
    @Autowired
    private MeMerchantLinkUser21Mapper meMerchantLinkUser21Mapper;
    @Autowired
    private Merchant21Mapper merchant21Mapper;
    @Autowired
    private Terminal21Mapper terminal21Mapper;
    @Autowired
    private TerminalRate21Mapper terminalRate21Mapper;
    @Autowired
    private RpcYxyTerminalService yxyTerminalService;
    @Autowired
    private MeMerchantLimit21Mapper meMerchantLimit21Mapper;
    @Autowired
    private MerchantPledgeCashPolicyMapper merchantPledgeCashPolicyMapper;
    @Autowired
    private MerchantYxyApiService merchantYxyApiService;
    @Autowired
    private TransactionFundAccountJournalMapper transactionFundAccountJournalMapper;
    @Autowired
    private AllyActivateHierarchy21Mapper allyActivateHierarchy21Mapper;

    @RoutingDataSource(DataSources.SLAVE_DB)
    @Override
    public Result queryTradeDetail(TradeListDTO dto) {
        TradeListVO result = new TradeListVO();
        Map<String, List<TradeDetailVO>> tranMap = new LinkedHashMap<>();

        List<TradeDetailVO> tradeDetailVOS = null;
        if (PlatNoEnums.YXY.isEquals(dto.getPlatNo())) {
            String merchantUserBaseId = meMerchantLinkUser21Mapper.selectByAppUserBaseIdAndMerchantNo(
                    dto.getUserBaseId(), dto.getChannelId(),dto.getMerchantNo());
            if (StringUtils.isNotBlank(merchantUserBaseId)) {
                dto.setUserBaseId(merchantUserBaseId);
            }
            PageFrom.startPage(dto.getPageNum(), dto.getPageSize());
            tradeDetailVOS = transactionPayTransactionMapper.queryTradeListYxy(
                    dto, PayTransactionConfig.getTransTableIndex(dto.getUserBaseId()));
        }  else {
            PageFrom.startPage(dto.getPageNum(), dto.getPageSize());
            tradeDetailVOS = transactionPayTransactionMapper.queryTradeList(
                    dto, PayTransactionConfig.getTransTableIndex(dto.getUserBaseId()));
        }
        if (CollectionUtils.isNotEmpty(tradeDetailVOS)) {

            tradeDetailVOS.forEach(t -> {
                if (PlatNoEnums.YXY.isEquals(t.getPlatNo())) {
                    if (PayTransactionEnum.CardFlagEnum.WECHAT.getCode().equals(t.getCardFlag())) {
                        t.setBankNo("微信");
                    } else if (PayTransactionEnum.CardFlagEnum.ALIPAY.getCode().equals(t.getCardFlag())) {
                        t.setBankNo("支付宝");
                    } else if (StringUtils.isNotBlank(t.getBankNo()) && StringUtils.isNotBlank(t.getTransactionBank())) {
                        t.setBankNo(joinBankCard(t.getTransactionBank(), t.getBankNo()));
                    } else {
                        t.setBankNo("(" + StringUtils.right(t.getBankNo(), 4) + ")");
                    }
                    //查询是否提过额
                    MerchantTradeLimit21 merchantTradeLimit21 = meMerchantLimit21Mapper.queryIsRaiseByUserBaseId(dto.getUserBaseId(), t.getChannelId());
                    t.setIsRaiseLimit(Objects.nonNull(merchantTradeLimit21));
                } else if (StringUtils.isNotBlank(t.getBankNo()) && StringUtils.isNotBlank(t.getTransactionBank())) {
                    t.setBankNo(joinBankCard(t.getTransactionBank(), t.getBankNo()));
                } else {
                    t.setBankNo("(" + StringUtils.right(t.getBankNo(), 4) + ")");
                }
                t.setMposSignImageUrl(acmTransactionParams.getMposSignImageUrl() + "/" + t.getSid());

                //显示手续费
                if (t.getWithdrawalFee() == null
                        || t.getWithdrawalFee().compareTo(BigDecimal.ZERO) == 0) {
                    t.setWithdrawalFee(t.getTransactionFee());
                }
                //显示到账金额
                t.setWithdrawalAmount(t.getTransactionAmount());

                //前端成功  返回成功
                if (PayTransactionStatusEnum.STATUS_40.getCode().compareTo(t.getStatus()) == 0) {
                    t.setStatus(PayTransactionStatusEnum.STATUS_10.getCode());
                }

                //按日月分组
                LocalDateTime transactionTime = LocalDateTime
                        .parse(t.getTransactionTime(), DateTimeFormatter.ofPattern(
                                DateFormat.DATETIME_DEFAULT.getPartten()));
                String key = DateFormat.MONTH_DAY.format(transactionTime);
                List<TradeDetailVO> tranList = tranMap.get(key);

                if (CollectionUtils.isEmpty(tranList)) {
                    tranList = new ArrayList<>();

                    tranList.add(t);
                } else {
                    tranList.add(t);
                }

                tranMap.put(key, tranList);

            });
        }
        //查询本月交易额
        QueryMonthAmountDTO queryMonthAmountDTO = new QueryMonthAmountDTO();
        BeanUtils.copyProperties(dto, queryMonthAmountDTO);
        if (PlatNoEnums.YXY.isEquals(dto.getPlatNo())) {
            result.setMonthAmount
                    (transactionPayTransactionMapper.queryMonthAmountYxy(
                            queryMonthAmountDTO, PayTransactionConfig.getTransTableIndex(dto.getUserBaseId())));
        } else {
            result.setMonthAmount
                    (transactionPayTransactionMapper.queryMonthAmount(
                            queryMonthAmountDTO, PayTransactionConfig.getTransTableIndex(dto.getUserBaseId())));
        }


        List<TradeMonthVO> tradeMonthVOS = new ArrayList<>();
        for (Map.Entry<String, List<TradeDetailVO>> stringListEntry : tranMap.entrySet()) {
            TradeMonthVO tradeMonthVO = new TradeMonthVO();
            tradeMonthVO.setMonthDay(stringListEntry.getKey());
            tradeMonthVO.setDayTradeList(stringListEntry.getValue());
            tradeMonthVOS.add(tradeMonthVO);
        }
        result.setTradeList(tradeMonthVOS);
        return Result.builder().success(result);
    }

    /**
     * 拼接银行卡号
     */
    protected String joinBankCard(String bank, String cardNo) {
        return "(" + bank + org.apache.commons.lang3.StringUtils.substring(cardNo, cardNo.length() - 4, cardNo.length()) + ")";
    }

    @RoutingDataSource(DataSources.SLAVE_DB)
    @Override
    public Result<PageVO> queryBalanceList(BalanceListDTO dto) {
        KLog.info("【用户账户明细查询】入参:{}", dto.toJSON());
        PageFrom.startPage(dto.getPageNum(), dto.getPageSize());
        dto.setMonth(StringUtils.remove(dto.getMonth(), "-"));
        List<BalanceListVO> balancesFromdb = fundBillMapper.queryBalanceList(dto);
        if (balancesFromdb == null) {
            return Result.builder().successPage(balancesFromdb);
        }
        List<BalanceListVO> balanceListVOS = new ArrayList<>();
        if (PlatNoEnums.YXY.getCode().equals(dto.getPlatNo())) {
            for (int j = 0; j < balancesFromdb.size(); j++) {
                boolean addFlag = true;
                if (j == 0) {
                    balanceListVOS.add(balancesFromdb.get(j));
                    continue;
                }
                for (int k = 0; k < balanceListVOS.size(); k++) {
                    //激活返现2,3阶段才合并交易额
                    if (!FundBillType.TYPE_113.getType().equals(balancesFromdb.get(j).getType())
                            || !balancesFromdb.get(j).getOrderId().contains("-")){
                        continue;
                    }

                    String channelIdStr = balancesFromdb.get(j).getOrderId().split("-")[1];
                    String userBaseId = balancesFromdb.get(j).getOrderId().split("-")[0];
                    //非m40同产品2,3阶段合并交易额
                    if (!ChannelIdEnums.yxy_jl_m40.getCode().equals(new Short(channelIdStr))
                            && balancesFromdb.get(j).getType().equals(balanceListVOS.get(k).getType())
                            && channelIdStr.equals(balanceListVOS.get(k).getOrderId().split("-")[1])
                            && userBaseId.equals(balanceListVOS.get(k).getOrderId().split("-")[0])) {
                        balanceListVOS.get(k).setAmount(NumberUtil.bigDecimalAdd(balanceListVOS.get(k).getAmount(), balancesFromdb.get(j).getAmount()));
                        addFlag = false;
                    }
                }
                if (addFlag) {
                    balanceListVOS.add(balancesFromdb.get(j));
                }
            }
        } else {
            balanceListVOS = balancesFromdb;
        }
        for (BalanceListVO balance : balanceListVOS) {
            fmtBalanceListVO(balance, dto.getPlatNo());
        }
        return Result.builder().successPage(balanceListVOS);
    }

    @RoutingDataSource(DataSources.SLAVE_DB)
    @Override
    public Result<PageVO> queryBalanceListV2(BalanceListDTO dto) {

        KLog.info("【用户账户明细查询V2】入参:{}", dto.toJSON());
        PageFrom.startPage(dto.getPageNum(), dto.getPageSize());
        dto.setMonth(StringUtils.remove(dto.getMonth(), "-"));
        List<BalanceListVO> balanceListVOS = fundBillMapper.queryBalanceListV2(dto);
        if (CollectionUtils.isEmpty(balanceListVOS)) {
            return Result.builder().successPage(Collections.emptyList());
        }
        for (BalanceListVO balance : balanceListVOS) {
            fmtBalanceListVOV2(balance, dto.getPlatNo());
        }
        return Result.builder().successPage(balanceListVOS);

    }

    /**
     * 格式化余额明细
     */
    private void fmtBalanceListVO(BalanceListVO balance, Short platNo) {
        balance.setTypeName(FundBillType.getUserBillType(balance.getType()).getName());
        if (FundBillType.TYPE_160.isEquals(balance.getType())
                || FundBillType.TYPE_110.isEquals(balance.getType())
                || FundBillType.TYPE_111.isEquals(balance.getType())
                || FundBillType.TYPE_112.isEquals(balance.getType())
                || FundBillType.TYPE_113.isEquals(balance.getType())
                || FundBillType.TYPE_140.isEquals(balance.getType())
                || FundBillType.TYPE_141.isEquals(balance.getType())
                || FundBillType.TYPE_143.isEquals(balance.getType())
                || FundBillType.TYPE_460.isEquals(balance.getType())) {
            if (StringUtils.isBlank(balance.getOrderId())) {
                return;
            }

            String fromUserBaseId = balance.getOrderId().split("-")[0];
            String fromName = "";
            if (PlatNoEnums.YXY.isEquals(platNo)) {
                //订单号格式:e92e434caf1111eb9dd600163e0af08e-600-1-110
                String channelId = balance.getOrderId().split("-")[1];
                fromName = transactionUserMapper.getUserBaseByOrderId(fromUserBaseId, channelId,
                        PlatNoEnums.YXY.getCode());
                if(isPuzzle(fromName)){
                    GetRealPhoneDTO getRealPhoneDTO = new GetRealPhoneDTO();
                    getRealPhoneDTO.setUserBaseId(fromUserBaseId);
                    getRealPhoneDTO.setChannelId(Short.valueOf(channelId));
                    Result<String> realName = merchantYxyApiService.getRealName(getRealPhoneDTO);
                    if(realName.isSuccess()){
                        fromName = realName.getData();
                    } else {
                        fromName = fromName+ "（未在商户通实名）";
                    }
                }
            } else {
                UserBase userBase = userBaseMapper.selectByPrimaryKey(fromUserBaseId);
                if (Objects.nonNull(userBase)){
                    fromName = userBase.getUserName();
                }
            }
            balance.setFromName(fromName);
        }
        //每次增加提现类型需要新增提现类型
        if (FundBillType.TYPE_200.isEquals(balance.getType())
                || FundBillType.TYPE_210.isEquals(balance.getType())
                || FundBillType.TYPE_220.isEquals(balance.getType())
                || FundBillType.TYPE_230.isEquals(balance.getType())
                || FundBillType.TYPE_240.isEquals(balance.getType())
                || FundBillType.TYPE_250.isEquals(balance.getType())
                || FundBillType.TYPE_260.isEquals(balance.getType())) {
            FundAccountWithdrawPayment withdrawPayment = fundAccountWithdrawPaymentMapper.findByOrderSn(platNo, balance.getOrderId());
            if (Objects.nonNull(withdrawPayment)) {
                if (WithDrawStatusEnum.WITHDRAW_STATUS_SUCCESS.getCode().equals(withdrawPayment.getWithdrawStatus())) {
                    balance.setStatusDesc("提现成功");
                    balance.setSuccessTime(withdrawPayment.getSuccessDate());
                } else if (WithDrawStatusEnum.WITHDRAW_STATUS_FAIL.getCode().equals(withdrawPayment.getWithdrawStatus())) {
                    balance.setStatusDesc("提现失败");
                    balance.setDetail(withdrawPayment.getErrors());
                    balance.setSuccessTime(withdrawPayment.getSuccessDate());
                } else {
                    balance.setStatusDesc("待入账");
                }
            }
        }
    }

    /**
     * 格式化余额明细
     * @param balance 余额
     * @param platNo 平台
     */
    private void fmtBalanceListVOV2(BalanceListVO balance, Short platNo) {
        balance.setTypeName(FundBillType.getUserBillType(balance.getType()).getName());
        //为余额冲正定制名称
        if (FundBillType.TYPE_201.isEquals(balance.getType())) {
            balance.setTypeName("提现-返回资金");
            //矫正
            FundAccountJournal journal = transactionFundAccountJournalMapper.getLastFundAccountJournalByPlanId(platNo, balance.getFundAccountId(), balance.getFundAccountChangePlanId());
            if (Objects.nonNull(journal)) {
                balance.setBalance(journal.getAccountAmountWithdrawableAfterwards());
            }
        }
        if (FundBillType.TYPE_160.isEquals(balance.getType())
                || FundBillType.TYPE_110.isEquals(balance.getType())
                || FundBillType.TYPE_111.isEquals(balance.getType())
                || FundBillType.TYPE_112.isEquals(balance.getType())
                || FundBillType.TYPE_113.isEquals(balance.getType())
                || FundBillType.TYPE_140.isEquals(balance.getType())
                || FundBillType.TYPE_141.isEquals(balance.getType())
                || FundBillType.TYPE_143.isEquals(balance.getType())
                || FundBillType.TYPE_460.isEquals(balance.getType())) {
            if (StringUtils.isBlank(balance.getOrderId())) {
                return;
            }

            String orderId0 = balance.getOrderId().split("-")[0];
            String fromUserBaseId = StringUtils.right(orderId0, 32);
            String fromName = "";
            if (PlatNoEnums.YXY.isEquals(platNo)) {

                if (balance.getOrderId().split("-").length > 1) {
                    //订单号格式:JL2a6fb0019050411efb6780242ac140008-6500-110-113
                    //订单号格式:JL2a6fb0019050411efb6780242ac140008-6500-113
                    String channelId = balance.getOrderId().split("-")[1];
                    balance.setChannelName(ChannelIdEnums.getChannelNameByCode(Short.valueOf(channelId)));

                    // 查询一阶段激活返现奖励的记录
                    AllyActivateHierarchy21Example hierarchy21Example = new AllyActivateHierarchy21Example();
                    hierarchy21Example.createCriteria()
                            .andFromUserBaseIdEqualTo(fromUserBaseId)
                            .andHierarchyEqualTo(1)
                            .andChannelIdEqualTo(Short.valueOf(channelId));
                    List<AllyActivateHierarchy21> hierarchy21List = allyActivateHierarchy21Mapper.selectByExample(hierarchy21Example);
                    if (CollectionUtils.isNotEmpty(hierarchy21List)) {
                        fromName = hierarchy21List.get(0).getFromUserName();

                        if(isPuzzle(fromName)){
                            GetRealPhoneDTO getRealPhoneDTO = new GetRealPhoneDTO();
                            getRealPhoneDTO.setUserBaseId(fromUserBaseId);
                            getRealPhoneDTO.setChannelId(Short.valueOf(channelId));
                            Result<String> realName = merchantYxyApiService.getRealName(getRealPhoneDTO);
                            if(realName.isSuccess()){
                                fromName = realName.getData();
                            } else {
                                fromName = fromName+ "（未在商户通实名）";
                            }
                        }

                        if (FundBillType.TYPE_110.isEquals(balance.getType()) || FundBillType.TYPE_113.isEquals(balance.getType())) {
                            balance.setTerminalSn(hierarchy21List.get(0).getTerminalSn());
                            balance.setTerminalAllyUserName(hierarchy21List.get(0).getToUserName());
                        }
                    }

                }
            } else {
                UserBase userBase = userBaseMapper.selectByPrimaryKey(fromUserBaseId);
                if (Objects.nonNull(userBase)){
                    fromName = userBase.getUserName();
                }
            }
            balance.setFromName(fromName);
        }
        //每次增加提现类型需要新增提现类型
        if (FundBillType.TYPE_200.isEquals(balance.getType())) {
            FundAccountWithdrawPayment withdrawPayment = fundAccountWithdrawPaymentMapper.findByOrderSn(platNo, balance.getOrderId());
            if (Objects.nonNull(withdrawPayment)) {
                if (WithDrawStatusEnum.WITHDRAW_STATUS_SUCCESS.getCode().equals(withdrawPayment.getWithdrawStatus())) {
                    balance.setStatusDesc("提现成功");
                    balance.setSuccessTime(withdrawPayment.getSuccessDate());
                } else if (WithDrawStatusEnum.WITHDRAW_STATUS_FAIL.getCode().equals(withdrawPayment.getWithdrawStatus())) {
                    balance.setStatusDesc("提现失败");
                    balance.setDetail(withdrawPayment.getErrors());
                    balance.setSuccessTime(withdrawPayment.getSuccessDate());
                } else {
                    balance.setStatusDesc("处理中");
                }
            }
        }
    }
    /**
     * 快收查询余额明细
     */
    @RoutingDataSource(DataSources.SLAVE_DB)
    @Override
    public Result<PageVO> queryBalanceListKlks(KlksBalanceListDTO dto) {
        KLog.info("【快收用户账户明细查询】入参:{}", dto.toJSON());
        UserBaseExt userBaseExt = transactionUserMapper.getUserBaseExtByOtherUserId(dto.getKlksUserId(), PlatNoEnums.KLKS.getCode());
        BalanceListDTO balanceListDTO = new BalanceListDTO();
        BeanUtils.copyProperties(dto, balanceListDTO);
        balanceListDTO.setUserBaseId(userBaseExt.getUserBaseId());
        return queryBalanceList(balanceListDTO);
    }

    /**
     * 快收查询余额明细详情
     */
    @RoutingDataSource(DataSources.SLAVE_DB)
    @Override
    public BalanceListVO queryBalanceListDetailKlks(KlksBalanceListDetailDTO dto) {
        KLog.info("【快收查询余额明细详情】入参:{}", dto.toJSON());
        BalanceListVO balanceList = fundBillMapper.queryBalanceDetail(PlatNoEnums.KLKS.getCode(), dto.getFundBillId());
        fmtBalanceListVO(balanceList, PlatNoEnums.KLKS.getCode());
        return balanceList;
    }

    @Override
    public void sendProfitPayTransactionMq(PayTransaction payTransaction) {

        Terminal terminal = null;
        boolean isUnPledge = isUnPledge(payTransaction, terminal);

        KLog.info("开始发送计分润交易mq, 参数:{}", payTransaction.toJSON());
        try {
            //收益模块mq推送
            MqPayTransationDTO mqPayTransationDTO = new MqPayTransationDTO();
            mqPayTransationDTO.setUserId(payTransaction.getUserBaseId());
            mqPayTransationDTO.setMerchantNo(payTransaction.getMerchantNo());
            mqPayTransationDTO.setTransactionOrderNo(payTransaction.getOrderNo());
            mqPayTransationDTO.setTransactionAmount(payTransaction.getTransactionAmount());
            mqPayTransationDTO.setRate(payTransaction.getRate());
            mqPayTransationDTO.setTransactionTime(
                    LocalDateUtils.formatByDefaultFormat(payTransaction.getTransactionTime()));
            mqPayTransationDTO.setPlatNo(payTransaction.getPlatNo());
            mqPayTransationDTO.setChannelId(payTransaction.getChannelId());

            mqPayTransationDTO.setTerminalSn(payTransaction.getSn());
            Terminal21Example terminal21Example = new Terminal21Example();
            terminal21Example.createCriteria().andTerminalSnEqualTo(payTransaction.getSn());
            List<Terminal21> terminal21s = terminal21Mapper.selectByExample(terminal21Example);
            if (CollectionUtils.isEmpty(terminal21s)) {
                mqPayTransationDTO.setRateType(ShareLevelRateTypeEnums.vip.getRateType());
            } else {
                TerminalRate21Example terminalRate21Example = new TerminalRate21Example();
                terminalRate21Example.createCriteria().andTerminalRateIdEqualTo(terminal21s.get(0).getTerminalRateId());
                List<TerminalRate21> terminalRate21s = terminalRate21Mapper.selectByExample(terminalRate21Example);
                if (CollectionUtils.isEmpty(terminal21s)) {
                    mqPayTransationDTO.setRateType(ShareLevelRateTypeEnums.vip.getRateType());
                } else {
                    if(terminal21s.get(0).getChannelId() == 6705) {
                        if(payTransaction.getRate() == 48) {
                            mqPayTransationDTO.setRateType(ShareLevelRateTypeEnums.znp_scan_four.getRateType());
                        } else if(payTransaction.getRate() == 38) {
                            mqPayTransationDTO.setRateType(ShareLevelRateTypeEnums.znp_scan_three.getRateType());
                        }else if(payTransaction.getRate() == 60) {
                            mqPayTransationDTO.setRateType(ShareLevelRateTypeEnums.vip.getRateType());
                        }else  {
                            mqPayTransationDTO.setRateType(ShareLevelRateTypeEnums.standard.getRateType());
                        }
                    } else {
                        if (terminal21s.get(0).getChannelId() == 6900) {
                            mqPayTransationDTO.setRateType(ShareLevelRateTypeEnums.jhmp.getRateType());
//                            if(terminalRate21s.get(0).getTerminalRateNormalValue() == 38) {
//                                mqPayTransationDTO.setRateType(ShareLevelRateTypeEnums.standard.getRateType());
//                            } else {
//                                mqPayTransationDTO.setRateType(ShareLevelRateTypeEnums.vip.getRateType());
//                            }
                        } else {
                            if(terminalRate21s.get(0).getTerminalRateNormalValue() == 63) {
                                mqPayTransationDTO.setRateType(ShareLevelRateTypeEnums.standard.getRateType());
                            } else {
                                mqPayTransationDTO.setRateType(ShareLevelRateTypeEnums.vip.getRateType());
                            }
                            if(Objects.equals(terminal21s.get(0).getChannelId(), ChannelIdEnums.YRB_LKL_EPOS.getCode()) || Objects.equals(terminal21s.get(0).getChannelId(), ChannelIdEnums.YRB_LKL_SPOS.getCode())) {
                                //拉卡拉扫码 万 15 上线
                                if(terminalRate21s.get(0).getTerminalRateId() == 33) {
                                    //拉卡拉（商户）上线 0.60+3 费率发万8
                                    mqPayTransationDTO.setRateType(ShareLevelRateTypeEnums.jhmp.getRateType());
                                }
                                if(Objects.equals(payTransaction.getRateStr(), "0.0048")) {
                                    mqPayTransationDTO.setRateType(ShareLevelRateTypeEnums.lkl.getRateType());
                                }
                            }
                        }
                    }
                }
            }
            //如果是57费率，不产生分润金额
            if(terminal21s.get(0).getTerminalRateId() == 34 || terminal21s.get(0).getTerminalRateId() == 35 || terminal21s.get(0).getTerminalRateId() == 36) {
                mqPayTransationDTO.setRateType(ShareLevelRateTypeEnums.free.getRateType());
            }
            //新分润方法规则，60费率发万三，63费率发万5
            //查询商户优惠标识
//            Merchant21Example merchant21Example = new Merchant21Example();
//            merchant21Example.createCriteria().andMerchantNoEqualTo(payTransaction.getMerchantNo())
//                    .andChannelIdEqualTo(payTransaction.getChannelId()).andPlatNoEqualTo(PlatNoEnums.YXY.getCode())
//                    .andIsDelEqualTo(Constant.NORMAL);
//            List<Merchant21> merchant21s = merchant21Mapper.selectByExample(merchant21Example);

//            if (CollectionUtils.isEmpty(merchant21s)) {
//                mqPayTransationDTO.setRateType(ShareLevelRateTypeEnums.standard.getRateType());
//            } else {
//                 //优惠费率过期标识 0:未过期 1:已过期
//                String discountsRatePastFlag = merchant21s.get(0).getDiscountsRatePastFlag();
//
//                // 费率是否固定（1:是 0:否）
//                String rateFixedFlag = merchant21s.get(0).getRateFixedFlag();
//
//                if (StringUtils.equals(MerchantEnum.RateFixedFlagEnum.STABILIZE.getCode(), rateFixedFlag)) {
//                    // 小陆微智能 固定费率时 按标准版算分润
//                    if (ChannelIdEnums.YRB_XIAOLU_SPOS.isEquals(merchant21s.get(0).getChannelId())) {
//                        mqPayTransationDTO.setRateType(ShareLevelRateTypeEnums.standard.getRateType());
//                    } else {
//                        mqPayTransationDTO.setRateType(ShareLevelRateTypeEnums.stabilize.getRateType());
//                    }
//
//                } else {
//                    // 非固定费率
//                    if (StringUtils.equals(MerchantEnum.DiscountsRatePastFlagEnum.EFFECTIVE.getCode(), discountsRatePastFlag)) {
//
//                        // 小陆微智能 vip时 按万5算分润
//                        if (ChannelIdEnums.YRB_XIAOLU_SPOS.isEquals(merchant21s.get(0).getChannelId())) {
//                            mqPayTransationDTO.setRateType(ShareLevelRateTypeEnums.stabilize.getRateType());
//                        } else {
//                            mqPayTransationDTO.setRateType(ShareLevelRateTypeEnums.vip.getRateType());
//                        }
//                    } else {
//                        mqPayTransationDTO.setRateType(ShareLevelRateTypeEnums.standard.getRateType());
//                    }
//                }
//            }

            //更新交易子表分润计算方式
            payTransaction.setProfitCalType(mqPayTransationDTO.getRateType());
            transactionPayTransactionMapper.updateByOrderNo(PayTransactionConfig.getTransTableIndex(payTransaction.getUserBaseId()), payTransaction);

            KLog.info("准备发送分润mq:{}", mqPayTransationDTO.toJSON());
            MqSendMessage mqSendMessage = new MqSendMessage();
            mqSendMessage.setTopic(MqEnum.MqTopicEnum.topic_trade_for_profit);
            mqSendMessage.setTag(MqEnum.MqTagEnum.tag_trade_for_profit);
            mqSendMessage.setSendMsg(mqPayTransationDTO.toJSON());
            mqSendMessage.setMessageKey(payTransaction.getOrderNo());
            mcenterMqService.send(mqSendMessage);
            //调用go判断直营交易量是否够50万增加标签
            String postUrl = "https://testapi.mugeyrb.com/transaction/account/profit/check?orderNum="+payTransaction.getOrderNo();
            if (commonService.isProd()) {
                postUrl = "http://172.17.187.6:8886/transaction/account/profit/check?orderNum="+payTransaction.getOrderNo();
            }
            try {
                HttpClientUtil.httpGetRequest(postUrl);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            KLog.error("【MQ-分润交易发送】异常:{}, orderNo:{}", e.getMessage(), payTransaction.getOrderNo(), e);
        }
        KLog.info("发送分润mq结束, orderNo:{}", payTransaction.getOrderNo());

    }

    @Override
    public List<JSONObject> allyFundBillType() {

        List<FundBillType> billTypeList = Arrays.asList(FundBillType.TYPE_110,FundBillType.TYPE_111,
                FundBillType.TYPE_113, FundBillType.TYPE_160,FundBillType.TYPE_170, FundBillType.TYPE_200, FundBillType.TYPE_201,
                FundBillType.TYPE_270,FundBillType.TYPE_271,FundBillType.TYPE_300, FundBillType.TYPE_450, FundBillType.TYPE_451,
                FundBillType.TYPE_452,FundBillType.TYPE_460,FundBillType.TYPE_470);

        List<JSONObject> billTypeJsonList = new ArrayList<>();
        for (FundBillType fundBillType : billTypeList) {
            JSONObject fundBillJson = new JSONObject();
            fundBillJson.put("name", fundBillType.getName().replace("余额冲正", "提现-返回资金"));
            fundBillJson.put("type", fundBillType.getType());
            billTypeJsonList.add(fundBillJson);
        }
        return billTypeJsonList;
    }

    /**
     * 查询是否为长春免押机具
     * @param payTransaction
     * @param terminal
     * @return
     */
    private boolean isUnPledge(PayTransaction payTransaction, Terminal terminal) {
        if (PlatNoEnums.YXY.isEquals(payTransaction.getPlatNo()) &&
                ChannelIdEnums.yxy_lkl_p40.isEquals(payTransaction.getChannelId())) {
            RpcYxyTerminalToBindDTO bindDTO = new RpcYxyTerminalToBindDTO();
            bindDTO.setSn(payTransaction.getSn());
            bindDTO.setUserBaseId(payTransaction.getUserBaseId());
            try {
                Result<Terminal> bindResult = yxyTerminalService.bind(bindDTO);

                if (!bindResult.isSuccess()) {
                    KLog.info("【P35支付通知】绑定机具失败,查询已绑定的机具:{},payTransaction:{}", bindResult.getDesc(), payTransaction.toJSON());
                    RpcYxyTerminalBindDTO rpcYxyTerminalBindDTO = new RpcYxyTerminalBindDTO();
                    rpcYxyTerminalBindDTO.setBindUserBaseId(payTransaction.getUserBaseId());
                    rpcYxyTerminalBindDTO.setChannelId(payTransaction.getChannelId());
                    rpcYxyTerminalBindDTO.setTerminalSn(payTransaction.getSn());

                    Result<Terminal> getBindResult = yxyTerminalService.getBind(rpcYxyTerminalBindDTO);
                    if (!getBindResult.isSuccess()) {
                        KLog.warn("【P35支付通知】查询绑定机具失败:{},payTransaction:{}", bindResult.getDesc(), payTransaction.toJSON());
                    }
                    terminal = getBindResult.getData();
                } else {
                    terminal = bindResult.getData();
                }
            } catch (Exception e) {
                KLog.error(BizCodeMessages.UNKNOWN_ERROR, "电销查询绑机异常:{}", e);
                return false;
            }

            //是否免押
            try {
                //查询机具策略
                if (BigDecimal.ZERO.compareTo(merchantPledgeCashPolicyMapper
                        .selectByPrimaryKey(terminal.getMerchantPledgeCashPolicyId()).getPledgeCashPayAmount()) == 0) {
                    return true;
                }
            } catch (Exception e) {
                KLog.error("获取机具策略失败", e);
                return false;
            }
        }
        return false;
    }

    /**
     * 判断是否脱敏
     * @param realName
     * @return true:是脱敏  false:非脱敏
     */
    private boolean isPuzzle(String realName){
       return StringUtils.equals(StringUtils.right(realName, 1),"*");
    }
}